import { ProForm } from '@ant-design/pro-components';
import { useEffect, useState } from 'react';
import UserDetailDrawer from './components/UserDetailDrawer';

interface Props {
  open: boolean;
  data: API.UserDetailInfo;
  onClose: () => void;
}

export default ({ open, data, onClose }: Props) => {
  const [form] = ProForm.useForm();
  const [currentData, setCurrentData] = useState<API.UserDetailInfo>(data);

  useEffect(() => {
    setCurrentData(data);
  }, [data]);

  useEffect(() => {
    if (!open) {
      form.resetFields();
      return;
    }

    if (currentData) {
      console.log('详情:', currentData);

      // 使用 form.setFieldsValue 设置初始值
      const formValues: any = {
        name: currentData.name || '',
      };

      // 设置手机信息的初始值
      if (currentData.phones && currentData.phones.length > 0) {
        currentData.phones.forEach((phone, index) => {
          formValues[`phone_${index}_model`] = phone.phone || '';
          formValues[`phone_${index}_brand`] = phone.ref?.brand || '';
          formValues[`phone_${index}_price`] = phone.ref?.price || '';
          formValues[`phone_${index}_color`] = phone.ref?.color || '';
        });
      }

      form.setFieldsValue(formValues);
      console.log('设置查看模式表单初始值:', formValues);
    }
  }, [currentData, open, form]);

  const handleDataChange = (newData: API.UserDetailInfo) => {
    setCurrentData(newData);
    console.log('查看模式数据已更新:', newData);
  };

  const onOk = async (values: any) => {
    console.log(values);
  };

  return (
    <UserDetailDrawer
      title="详情"
      data={currentData}
      readonly={true}
      form={form}
      onClose={onClose}
      open={open}
      onOk={onOk}
      onDataChange={handleDataChange}
    />
  );
};
